package com.huashi.dealer.modular.business.upload.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huashi.dealer.commonEntity.UploadFile;
import com.huashi.dealer.core.exception.CommonException;
import com.huashi.dealer.core.util.FileUploadUtil;
import com.huashi.dealer.modular.business.upload.mapper.UploadFileMapper;
import com.huashi.dealer.modular.business.upload.service.UploadService;
import com.huashi.dealer.modular.business.upload.param.UploadResponseParam;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * API上传Service实现类
 *
 * @author 谭陈强
 * @since 2025-07-30
 */
@Service("apiUploadServiceImpl")
public class UploadServiceImpl extends ServiceImpl<UploadFileMapper, UploadFile> implements UploadService {
    public static final String WXAPPPID = "10001";
    
    @Autowired
    private UploadService uploadFileService;

    @Resource
    private FileUploadUtil fileUploadUtil;
    @Override
    public UploadFile uploadImage(MultipartFile file) {
        UploadFile uploadFile=new UploadFile();
        try {
            // 验证用户登录
            if (!StpUtil.isLogin()) {
                throw new CommonException("用户未登录");
            }
            
            // 获取当前用户的小程序ID
            Long wxappId = Long.valueOf(WXAPPPID);
            uploadFile = fileUploadUtil.uploadImage(file);
            uploadFile.setWxappId(wxappId);
            this.save(uploadFile);
            
        } catch (Exception e) {
            throw new CommonException("图片上传失败：" + e.getMessage());
        }
        
        return uploadFile;
    }

    @Override
    public UploadResponseParam uploadFile(MultipartFile file) {
        UploadResponseParam responseParam = new UploadResponseParam();
        
        try {
            // 验证用户登录
            if (!StpUtil.isLogin()) {
                throw new CommonException("用户未登录");
            }
            
            // 使用传入的wxappId，如果没有则使用默认值
            Long appId = Long.valueOf(WXAPPPID);
            
            // 上传文件并保存到数据库
            UploadFile uploadFile = uploadFileService.uploadImage(file);
            
            // 构建响应
            responseParam.setFileId(uploadFile.getFileId());
            responseParam.setFilePath(uploadFile.getFileName()); // 文件路径
            responseParam.setFileUrl(uploadFile.getFileUrl());
            responseParam.setFileName(uploadFile.getFileName()); // 文件路径作为文件名
            responseParam.setFileType(uploadFile.getFileType());
            responseParam.setFileSize(uploadFile.getFileSize());
            responseParam.setStorage(uploadFile.getStorage());
            responseParam.setGroupId(uploadFile.getGroupId());
            responseParam.setFileStatus(10); // 正常状态
            responseParam.setCreateTime(uploadFile.getCreateTime());
            
        } catch (Exception e) {
            throw new CommonException("文件上传失败：" + e.getMessage());
        }
        
        return responseParam;
    }

    @Override
    public UploadResponseParam uploadImages(MultipartFile[] files, String token, Long wxappId) {
        UploadResponseParam responseParam = new UploadResponseParam();
        
        try {
            if (files == null || files.length == 0) {
                throw new CommonException("上传文件不能为空");
            }
            
            // 验证用户登录
            if (!StpUtil.isLogin()) {
                throw new CommonException("用户未登录");
            }
            
            // 使用传入的wxappId，如果没有则使用默认值
            Long appId = wxappId != null ? wxappId : Long.valueOf(WXAPPPID);
            
            // 批量上传图片
            List<UploadResponseParam.FileInfo> fileList = new ArrayList<>();
            int successCount = 0;
            int failCount = 0;
            
            for (MultipartFile file : files) {
                if (file != null && !file.isEmpty()) {
                    try {
                        // 上传单个文件
                        UploadFile uploadFile = uploadFileService.uploadImage(file);
                        
                        // 构建文件信息
                        UploadResponseParam.FileInfo fileInfo = new UploadResponseParam.FileInfo();
                        fileInfo.setFileId(uploadFile.getFileId());
                        fileInfo.setFilePath(uploadFile.getFileName()); // 文件路径
                        fileInfo.setFileUrl(uploadFile.getFileUrl());
                        fileInfo.setFileName(uploadFile.getFileName()); // 文件路径作为文件名
                        fileInfo.setFileType(uploadFile.getFileType());
                        fileInfo.setFileSize(uploadFile.getFileSize());
                        fileInfo.setStorage(uploadFile.getStorage());
                        fileInfo.setGroupId(uploadFile.getGroupId());
                        fileInfo.setFileStatus(10); // 正常状态
                        fileInfo.setCreateTime(System.currentTimeMillis()/1000);
                        
                        fileList.add(fileInfo);
                        successCount++;
                    } catch (Exception e) {
                        failCount++;
                    }
                } else {
                    failCount++;
                }
            }
            
            responseParam.setFileList(fileList);
            responseParam.setSuccessCount(successCount);
            responseParam.setFailCount(failCount);
            responseParam.setTotal((long) files.length);
            
        } catch (Exception e) {
            throw new CommonException("批量上传图片失败：" + e.getMessage());
        }
        
        return responseParam;
    }

    @Override
    public void deleteFile(Long fileId) {
        try {
            // 验证用户登录
            if (!StpUtil.isLogin()) {
                throw new CommonException("用户未登录");
            }
            
            if (fileId == null) {
                throw new CommonException("文件ID不能为空");
            }
            
            // 将字符串ID转换为Long
            Long id = Long.valueOf(fileId);
            
            // 删除文件（包括物理文件和数据库记录）
            this.baseMapper.deleteById(id);

            
        } catch (NumberFormatException e) {
            throw new CommonException("文件ID格式错误");
        } catch (Exception e) {
            throw new CommonException("删除文件失败：" + e.getMessage());
        }
    }

    @Override
    public UploadResponseParam getFileInfo(String fileId, String token) {
        UploadResponseParam responseParam = new UploadResponseParam();
        
        try {
            if (fileId == null || fileId.isEmpty()) {
                throw new CommonException("文件ID不能为空");
            }
            
            // 将字符串ID转换为Long
            Long id = Long.valueOf(fileId);
            
            // 从数据库查询文件信息
            UploadFile uploadFile = uploadFileService.getById(id);
            if (uploadFile == null) {
                throw new CommonException("文件不存在");
            }
            
            // 构建文件信息
            UploadResponseParam.FileInfo fileInfo = new UploadResponseParam.FileInfo();
            fileInfo.setFileId(uploadFile.getFileId());
            fileInfo.setFilePath(uploadFile.getFileName()); // 文件路径
            fileInfo.setFileUrl(uploadFile.getFileUrl());
            fileInfo.setFileName(uploadFile.getFileName()); // 文件路径作为文件名
            fileInfo.setFileType(uploadFile.getFileType());
            fileInfo.setFileSize(uploadFile.getFileSize());
            fileInfo.setStorage(uploadFile.getStorage());
            fileInfo.setGroupId(uploadFile.getGroupId());
            fileInfo.setFileStatus(10); // 正常状态
            fileInfo.setCreateTime(uploadFile.getCreateTime());
            
            responseParam.setFileInfo(fileInfo);
            
        } catch (NumberFormatException e) {
            throw new CommonException("文件ID格式错误");
        } catch (Exception e) {
            throw new CommonException("获取文件信息失败：" + e.getMessage());
        }
        
        return responseParam;
    }

    @Override
    public UploadResponseParam checkFile(String filePath, String token) {
        UploadResponseParam responseParam = new UploadResponseParam();
        
        try {
            if (filePath == null || filePath.isEmpty()) {
                throw new CommonException("文件路径不能为空");
            }
            
            // 验证用户登录
            if (!StpUtil.isLogin()) {
                throw new CommonException("用户未登录");
            }
            
            // 根据文件路径查询文件是否存在
            // 这里可以通过文件名查询数据库记录
            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
//            Long fileId = uploadFileService.getFileIdByName(fileName);
//
//            responseParam.setFileExists(fileId != null);
            
        } catch (Exception e) {
            throw new CommonException("检查文件失败：" + e.getMessage());
        }
        
        return responseParam;
    }
} 